package gfdclient;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.File;
import java.rmi.registry.Registry;
import javax.swing.*;

/**
 *
 * @author Volk, Ustinov
 */
public class ConnectWindow extends JDialog {

    //------------------Inner attributes----------------------------------
    String inetAddress = null;
    //--------------------------------------------------------------------
    /**
     *
     * @param address - internet addres, you wish to set in combobox
     */
    public void setInetAddress(String address)
    {
        inetAddress = address;
        if (inetAddress != null) comboInetAddress.addItem(inetAddress);
    }

    //----------Inner methood------------------------------

      /**
   * Преобразровать URL адрес в RMI адрес
   * @param inetAddress - адрес хоста
   * @param port - адрес порта
   * @param stubName - имя заглушки
   */
  private String transformToRMIURL(String inetAddress, int port, String stubName){
     inetAddress.trim();
     if(inetAddress.contains("/" + stubName)) inetAddress = inetAddress.substring(0, inetAddress.length() - stubName.length() - "/".length());
     inetAddress+= ":" + port + "/"+ stubName;

     if( (!inetAddress.contains("http") && (!inetAddress.contains("rmi")) )) inetAddress = "rmi:" + "/" + "/" + inetAddress;
     else inetAddress =  inetAddress.replace("http", "rmi");
     return inetAddress;
  }


    private void _setLocation(){
        Toolkit tk = Toolkit.getDefaultToolkit();
        Dimension dm = tk.getScreenSize();
        int xPos = dm.width/2 - getWidth()/2;
        int yPos = dm.height/2 - getHeight()/2;
        setLocation(xPos,yPos);
    }

    @Override
    public void setVisible(boolean b) {
        super.setVisible(b);
    }

    /** Creates new form ConnectWindow */
    public ConnectWindow(JFrame owner) {
        super(owner, true);
        initComponents();
        _setLocation();
        setTitle("Настройки сетевого соединения");
    }

    public ConnectWindow(JDialog owner){
        super(owner, true);
        initComponents();
        _setLocation();
        setTitle("Настройки сетевого соединения");
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        labelConnect = new javax.swing.JLabel();
        labelPort = new JLabel();

        comboInetAddress = new javax.swing.JComboBox();
        btnSave = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();

        labelPort.setText("Порт:");
        fieldPort = new JTextField(""+Registry.REGISTRY_PORT);

        labelConnect.setText("Введите адрес сервера:");
        labelConnect.setToolTipText("Адрес сервера - уникальный идентификатор сервера в сети интернет");

        comboInetAddress.setEditable(true);
        comboInetAddress.setToolTipText("Введите в данной поле адрес сервера или выбирите его из списка");

        btnSave.setText("Принять");
        btnSave.setToolTipText("Если вы хотите сохранить внесённые вами изменения в системе и использовать выбранный сервер в качестве подключения по умолчанию  нажмите на этой кнопке");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        btnCancel.setText("Отмена");
        btnCancel.setToolTipText("Если вы не хотите чтобы ваши изменения были сохранены в системе нажмите по этой кнопке");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(fieldPort, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(labelPort, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 229, Short.MAX_VALUE)
                         .addComponent(comboInetAddress, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(labelConnect, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 229, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnSave)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnCancel)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(labelConnect)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(comboInetAddress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addContainerGap()
                .addComponent(labelPort)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(fieldPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCancel)
                    .addComponent(btnSave))
                .addContainerGap(18, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    //обработчик нажатия сохранения настроек
    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        inetAddress = (String)comboInetAddress.getSelectedItem();
        inetAddress = this.transformToRMIURL(inetAddress, Integer.parseInt(fieldPort.getText()), "USCProxy");
    
        setVisible(false);
    }//GEN-LAST:event_btnSaveActionPerformed

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
       setVisible(false);
    }//GEN-LAST:event_btnCancelActionPerformed

    //---------------------Setter and getter-----------------------------------
    /**
     * Получить текущий адрес хоста
     * @return текущий адрес хоста или null если интернет адрес не установлен
     */
    public String getAddress(){return inetAddress;}
    //-------------------------------------------------------------------------

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnSave;
    private javax.swing.JComboBox comboInetAddress;
    private javax.swing.JLabel labelConnect;
    private JLabel labelPort;
    private JTextField fieldPort;
    // End of variables declaration//GEN-END:variables

}
